package com.example.wanxiang.service.Impl;

import com.example.wanxiang.dto.GroupDto;
import com.example.wanxiang.entity.Group;
import com.example.wanxiang.repository.GroupRepository;
import com.example.wanxiang.service.GroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service("groupService")
public class GroupServiceImpl implements GroupService {

    @Autowired
    private GroupRepository groupRepository;

    @Override
    public Group create(GroupDto groupDto) {
       Group group = new Group();
       group.setGroupName(groupDto.getGroupName());
       group.setStatus(true);
       group.setUserIds(groupDto.getUserIds());
       group.setUserId(groupDto.getUserId());
       return groupRepository.save(group);
    }

    @Override
    public Group delete(String id) {
        Group group = groupRepository.findById(id).orElse(null);
        if (group != null)
        groupRepository.deleteById(id);
        return group;
    }

    @Override
    public Group getByGroupName(String groupName) {
        return groupRepository.findByGroupName(groupName);
    }

    @Override
    public Group update(String id, GroupDto groupDto) {
        Group group = groupRepository.findById(id).orElse(null);
        if (group != null)
        {
            group.setGroupName(groupDto.getGroupName());
            group.setStatus(groupDto.isStatus());
            List<Long> userIds = group.getUserIds();
            userIds.add(groupDto.getNewsId());
            group.setUserIds(userIds);
            group.setUserId(groupDto.getUserId());
            groupRepository.save(group);
        }
        return group;
    }
}
